package com.base.framework.base.converter;

import com.base.commons.web.utils.PropertyUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
import com.fasterxml.jackson.datatype.joda.JodaModule;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * 将日期转换为JSON
 * Created by Irany(欧书剑) 2017/7/19 0019 20:00
 */
public class RedObjectMapper extends ObjectMapper {
    public RedObjectMapper(){
        super();

        Hibernate4Module module=new Hibernate4Module();
        module.configure(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION,false);
        this.setTimeZone(TimeZone.getDefault());
        this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .configure(SerializationFeature.INDENT_OUTPUT,true)
                .registerModule(module)
                .registerModule(new JodaModule());

        //允许单引号
        if (PropertyUtil.isTrue("base.json.ALLOW_SINGLE_QUOTES","0")){
            this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
        }

        //字段和值都加引号
        if (PropertyUtil.isTrue("base.json.ALLOW_UNQUOTED_FIELD_NAMES","0")){
            this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
        }

        //数字作为字符串输出
        if (PropertyUtil.isTrue("base.json.WRITE_NUMBERS_AS_STRINGS","0")){
            this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS,true);
        }

        //空值处理为空字符串
        if (PropertyUtil.isTrue("base.json.QUOTE_NON_NUMERIC_NUMBERS","0")){
            this.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN,true);
        }

        //NULL处理为空字符串
        if (PropertyUtil.isTrue("base.json.WRITE_NULL_AS_BLANK","0")){
            SerializerProvider sp=this.getSerializerProvider();
            sp.setNullValueSerializer(new JsonSerializer<Object>() {
                @Override
                public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
                    gen.writeString("");
                }
            });
        }

      /*  #json转换
#允许单引号
        base.json.ALLOW_SINGLE_QUOTES=false
#字段和值都加引号
        base.json.ALLOW_UNQUOTED_FIELD_NAMES=false
#数字作为字符串输出
        base.json.WRITE_NUMBERS_AS_STRINGS=false
#空值处理为空串
        base.json.QUOTE_NON_NUMERIC_NUMBERS=false
#NULL处理为空串
        base.json.WRITE_NULL_AS_BLANK=false

#关闭Ehcache自动检测更新
        net.sf.ehcache.skipUpdateCheck=true*/
    }
}
